package com.aqa.concurrent;

import org.junit.Test;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class SemaphoreTest {


    @Test
    public void testAcquire() {

        try {
            Semaphore semaphore = new Semaphore(3);
            semaphore.acquire(1);
            Thread thread = new Thread(() -> {
                try {
                    semaphore.acquire(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            Thread thread2 = new Thread(() -> {
                try {
                    semaphore.acquire(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
            thread2.start();
            semaphore.release(3);
            Thread.currentThread().join();
            System.out.println("--------------Semaphore----------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Test
    public void test2Semp() throws InterruptedException {
        Semaphore semaphore = new Semaphore(2);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
        IntStream.range(1, 5).forEach(i -> {
            pool.submit(() -> {
                try {
                    System.out.println("------ 线程启动：" + Thread.currentThread().getName() + " ------ ");
                    semaphore.acquire();
                    System.out.println("------ 线程阻塞停止：" + Thread.currentThread().getName() + " ------ ");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        });

        semaphore.release();
        Thread.currentThread().join();

    }


}
